package com.suncaper.han_yi_system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suncaper.han_yi_system.exception.CustomerException;
import com.suncaper.han_yi_system.pojo.dto.ResetPasswordDto;
import com.suncaper.han_yi_system.pojo.dto.UserDto;
import com.suncaper.han_yi_system.pojo.dto.UserQueryDto;
import com.suncaper.han_yi_system.pojo.entity.LoginUser;
import com.suncaper.han_yi_system.pojo.entity.User;
import com.suncaper.han_yi_system.mapper.UserMapper;
import com.suncaper.han_yi_system.pojo.vo.UserVo;
import com.suncaper.han_yi_system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Page<UserVo> pageList(UserQueryDto userQueryDto) {
        Page<UserVo> page = new Page<>(userQueryDto.getPage(), userQueryDto.getLimit());
        Page<UserVo> list = baseMapper.pageList(page, userQueryDto);
        return list;
    }


    @Override
    @Transactional
    public void saveUser(UserDto userDto) {
        userDto.setPassword(passwordEncoder.encode(userDto.getPassword()));
        baseMapper.insert(userDto);
        baseMapper.insertUserRole(userDto.getId(), userDto.getRoleId());
    }

    @Override
    @Transactional
    public void updateUser(UserDto userDto) {
        // 如果密码字段不为空，则进行加密
        if (StringUtils.hasText(userDto.getPassword())) {
            userDto.setPassword(passwordEncoder.encode(userDto.getPassword()));
        } else {
            // 密码为空时，保持原密码不变
            User existingUser = baseMapper.selectById(userDto.getId());
            userDto.setPassword(existingUser.getPassword());
        }
        baseMapper.updateById(userDto);
        baseMapper.deleteUserRole(userDto.getId());
        baseMapper.insertUserRole(userDto.getId(), userDto.getRoleId());
    }

    @Override
    @Transactional
    public void removeUser(Long id) {
        baseMapper.deleteById(id);
        baseMapper.deleteUserRole(id);
    }

    @Override
    public void resetPassword(ResetPasswordDto userDto) {
        User user = baseMapper.selectById(userDto.getId());
        if (user != null) {
            if (passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
                if (passwordEncoder.matches(userDto.getNewPassword(), user.getPassword())) {
                    throw new CustomerException("新密码不能与旧密码相同");
                } else if (!userDto.getConfirmPassword().equals(userDto.getNewPassword())) {
                    throw new CustomerException("两次输入的密码不一致");
                } else {
                    user.setPassword(passwordEncoder.encode(userDto.getNewPassword()));
                    baseMapper.updateById(user);
                }
            } else {
                throw new CustomerException("密码修改失败");
            }
        } else {
            throw new CustomerException("密码修改失败");
        }

    }

    @Override
    public List<UserVo> getUserByRole() {
        return getBaseMapper().findUserByRole();
    }

    @Override
    public UserVo getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();

        return getBaseMapper().findCurrentUser(userId);

    }

}
